import { Node, error, instantiate, log, NodePool, Prefab, v3 } from 'cc';
import Utils from '../utils/Utils';
import Singleton from './Singleton';

export default class PoolMgr extends Singleton {

    pools: any = {};
    prefabs: any = {};
    async loadPrefabs() {
        let list = [
            { path: "items/Coin", bundle: "prefabs", key: "Coin", cn: 3 },
            { path: "items/Life", bundle: "prefabs", key: "Life", cn: 3 },
            { path: "items/Star", bundle: "prefabs", key: "Star", cn: 3 },
        ];

        try {
            for (var i = 0; i < list.length; ++i) {
                let a = list[i];
                let ret: any = await Utils.loadRes(a.path, a.bundle, Prefab);
                this.initPool(a.key, ret, a.cn);
            }
        } catch (error) {
            console.error(error)
        }
    }


    initPool(key: any, prefab: Prefab, count: number) {
        // console.log("initPool:",key,count);
        this.prefabs[key] = prefab;
        this.pools[key] = new NodePool();
        for (var i = 0; i < count; ++i) {
            this.pools[key].put(instantiate(prefab));
        }
    }

    get(key: any): Node {
        if (this.pools[key] == null) {
            error("没有" + key);
            return null;
        }
        if (!this.getputcount[key]) this.getputcount[key] = 0;
        this.getputcount[key]++

        if (this.pools[key].size() > 0)
            return this.pools[key].get();
        else
            return instantiate(this.prefabs[key]);
    }

    getputcount = {};
    put(key: any, node: Node) {
        if (!this.getputcount[key])
            this.getputcount[key] = 0;
        this.getputcount[key]--

        if (!this.pools[key]) {
            console.error(key)
        }
        this.pools[key].put(node);
    }

    trace() {
        for (var key in this.pools) {
            log(key, this.pools[key].size())
        }
    }
}

window['PoolMgr'] = PoolMgr;

